package com.itheima.shop.interceptor;

import com.itheima.shop.user.SessionShare;
import com.itheima.shop.user.SessionThreadLocal;
import com.itheima.shop.util.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @program: design
 * @description:
 * @author: zhanghz001
 * @create: 2020-12-15 10:02
 **/
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Autowired
    private SessionThreadLocal sessionThreadLocal;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String token = request.getHeader("token");
            if (!StringUtils.isEmpty(token)) {
                Map<String, Object> tokenMap = JwtTokenUtil.parseToken(token);
                //封装用户身份信息，存储到ThreadLocal中，供当前线程共享使用
                //1.封装需要共享的信息
                //2.创建一个对象继承封装信息，每次共享该对象 (不需要共享，则可以创建另外一个对象继承它)
                //3.创建共享管理对象，实现共享信息的增加、获取、移除功能 
                SessionShare share = new SessionShare(
                        tokenMap.get("username").toString(),
                        tokenMap.get("name").toString(),
                        tokenMap.get("sex").toString(),
                        tokenMap.get("role").toString(),
                        Integer.valueOf(tokenMap.get("level").toString()));
                sessionThreadLocal.addSession(share);
                return true;
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setContentType("application/json;chaset=utf-8");
        response.getWriter().write("身份验证失败!");
        response.getWriter().close();
        return false;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        sessionThreadLocal.remove();
    }
}
